package com.yxzx.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.yxzx.common.YxzxResult;
import com.yxzx.vod.service.VidService;
import com.yxzx.vod.util.AliyunVODSDKUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * Copyright (C), 2018-2020
 * FileName: VideoController
 * Author:   kongfanyu
 * Date:     2020/8/14 10:40
 */
@Slf4j
@Api(tags = "阿里云视频上传管理")
@CrossOrigin
@RestController
@RequestMapping("/vidservice/vod")
public class VideoController {

    @Autowired
    private VidService vidService;

    @ApiOperation("获取播放凭证")
    @GetMapping("getPlayAuth/{vid}")
    public YxzxResult getPlayAuth(@ApiParam(name = "vid",value = "视频ID", required = true) @PathVariable String vid){
        DefaultAcsClient client = AliyunVODSDKUtils.initVodClient();
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setAuthInfoTimeout(3000L);
        request.setVideoId(vid);
        try {
            response = client.getAcsResponse(request);
            //播放凭证
            return YxzxResult.ok().data("playAuth",response.getPlayAuth());
        } catch (Exception e) {
            log.error("ErrorMessage = " + e.getLocalizedMessage());
            return YxzxResult.error();
        }
    }


    @ApiOperation("上传视频")
    @PostMapping("upload")
    public YxzxResult uploadVideo(@ApiParam(name = "file",value = "视频文件", required = true) MultipartFile file){
        String videoId = vidService.uploadVideo(file);
        return videoId != null ?  YxzxResult.ok().data("item",videoId) : YxzxResult.error();
    }

    @ApiOperation("删除视频")
    @DeleteMapping("{videoId}")
    public YxzxResult deleteVideo(@ApiParam(name = "videoId",value = "视频文件Id", required = true)@PathVariable String videoId){
        vidService.deleteVideo(videoId);
        return YxzxResult.ok();
    }

    @ApiOperation("删除多个阿里云视频")
    @DeleteMapping("deleteBatch")
    public YxzxResult deleteVideoList(@ApiParam(name = "videoList",value = "云端视频id",required = true)
                                          @RequestParam("videoList") List<String> videoList){
        String videoIds = StringUtils.join(videoList.toArray(), ',');
        vidService.deleteVideo(videoIds);
        return YxzxResult.ok().message("视频删除成功");
    }

}
